package com.quectel.cms.controller.grid;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.controller.grid.helper.GridHelper;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.grid.GridPolygonPathVo;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.grid.dto.GridBindingDto;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridMemberGridBindingDto;
import com.quectel.core.module.grid.dto.GridRegionInfoDto;
import com.quectel.core.module.grid.service.GridBindingService;
import com.quectel.core.module.grid.service.GridMemberGridBindingService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.core.module.really.dto.ReallyCompanyDto;
import com.quectel.core.module.really.service.ReallyCompanyService;
import com.quectel.core.module.village.dto.VillageBuildingDto;
import com.quectel.core.module.village.service.VillageBuildingService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/02/03 15:45
 */
@RestController
@RequestMapping("grid")
@Tag(name = "GridController", description = "网格信息管理表相关api")
public class GridController extends BaseController {

    public static final String NOT_IN = "notIn";

    @DubboReference
    private GridService gridService;
    @DubboReference
    private VillageBuildingService villageBuildingService;
    @DubboReference
    private GridBindingService gridBindingService;
    @DubboReference
    private ReallyCompanyService reallyCompanyService;
    @DubboReference
    private GridMemberGridBindingService gridMemberGridBindingService;

    @Autowired
    private GridHelper gridHelper;

    @GetMapping("queryGridBindSourceId")
    @Operation(summary = "根据资源类型查询绑定资源id列表")
    public Response<Object> queryGridBindSourceByType(
            @RequestParam(required = false) Byte sourceType) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        request.put(LambdaUtil.getFieldName(GridBindingDto::getSourceType), sourceType);
        List<GridBindingDto> gridBindingDtos = gridBindingService.queryList(request.getParams());
        return Response.ok().wrap(gridBindingDtos);
    }


    @GetMapping("queryGridBindSourceIdAndGridId")
    @Operation(summary = "根据条件查询绑定资源id列表")
    public Response<Object> queryGridBindSourceIdAndGridId(
            @RequestParam(required = false) Byte sourceType,
            @RequestParam(required = false) Long ownGridId) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));
        request.put(LambdaUtil.getFieldName(GridBindingDto::getSourceType), sourceType);
        request.put(NOT_IN, ownGridId);
        List<GridBindingDto> gridBindingDtos = gridBindingService.queryList(request.getParams());
        return Response.ok().wrap(gridBindingDtos);
    }

    /**
     * 查询登录用户层级
     *
     * @return
     */
    @GetMapping("queryRegion")
    @Operation(summary = "查询可绑定的街道/小区/网格")
    public Response<List<GridRegionInfoDto>> queryRegion() {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        LoginUserSession sysUser = SessionHolder.getSysUser();
        //查询下级区域
        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryRegionInfoByGroupId(sysUser.getGroupId());

        return Response.<List<GridRegionInfoDto>>ok().wrap(gridRegionInfoDtos);
    }

    /**
     * 查询下属的街道/小区/网格
     *
     * @return
     */
    @GetMapping("canSelectRegion")
    @Operation(summary = "查询可绑定的街道/小区/网格")
    public Response<List<GridRegionInfoDto>> canSelectRegion() {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        LoginUserSession sysUser = SessionHolder.getSysUser();
        //查询下级区域
        List<GridRegionInfoDto> gridRegionInfoDtos = gridHelper.queryChildRegionInfoByGroupId(sysUser.getGroupId());

        return Response.<List<GridRegionInfoDto>>ok().wrap(gridRegionInfoDtos);
    }


    /**
     * 查询租户下网格
     *
     * @return
     */
    @GetMapping("queryAll")
    @Operation(summary = "查询网格列表")
    public Response<List<GridDto>> queryAll() {
        Map<String, Object> params = Request.parseParams(httpServletRequest);
        super.fillAuthorityData(params);

        List<GridDto> list = gridService.queryList(params);
        if (CollectionUtils.isNotEmpty(list)) {
            for (GridDto grid : list) {
                String extraAttr = grid.getExtraAttr();
                if (StringUtils.isNotBlank(extraAttr)) {
                    GridDto.ExtraAttrCls parse = JacksonUtils.parse(extraAttr, GridDto.ExtraAttrCls.class);
                    String polygonPath = parse.getPolygonPath();
                    if (StringUtils.isNotBlank(polygonPath)) {
                        List<GridPolygonPathVo> gridPolygonPathVos = JacksonUtils.parseArray(polygonPath, GridPolygonPathVo.class);
                        if (CollectionUtils.isNotEmpty(gridPolygonPathVos)) {
                            List<GridPolygonPathVo> myList = gridPolygonPathVos;
                            int numPoints = myList.size();
                            double[][] polygon = new double[numPoints][2];
                            for (int i = 0; i < numPoints; i++) {
                                GridPolygonPathVo gridPolygonPathVo = myList.get(i);
                                // 存储经度到数组的第一列
                                polygon[i][0] = gridPolygonPathVo.getLng();
                                // 存储纬度到数组的第二列
                                polygon[i][1] = gridPolygonPathVo.getLat();
                            }
                            double[] centerPoint = PolygonCenterPointUtil.getCenter(polygon);
                            grid.setCenterPoint(centerPoint);
                        }
                    }
                }

                Map<String, Object> countSql = new HashMap<>();
                countSql.put(LambdaUtil.getFieldName(GridMemberGridBindingDto::getGridId), grid.getId());
                int gridMemberNum = gridMemberGridBindingService.queryTotal(countSql);
                grid.setGridMemberNum(gridMemberNum);
            }
        }
        return Response.<List<GridDto>>ok().wrap(list);

    }

    @GetMapping("queryAllCompanies")
    @Operation(summary = "根据条件查询实有单位列表")
    public Response<List<ReallyCompanyDto>> queryAllCompanies(@RequestParam(required = false) Long villageId) {

        Map<String, Object> params = Request.parseParams(httpServletRequest);
        super.fillAuthorityData(params);

        List<ReallyCompanyDto> list = reallyCompanyService.queryList(params);

        return Response.<List<ReallyCompanyDto>>ok().wrap(list);
    }

    @GetMapping("bindBuilding")
    @Operation(summary = "查询网格楼栋列表")
    public Response<List<VillageBuildingDto>> bindBuilding(@RequestParam Long gridId, @RequestParam Long villageId) {
        Map<String, Object> params = Request.parseParams(httpServletRequest);
        // 查询已经被绑定的楼栋
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(LambdaUtil.getFieldName(GridBindingDto::getGridId), gridId);
        queryMap.put(LambdaUtil.getFieldName(GridBindingDto::getSourceType), GridConstant.SourceType.BUILDING.getType());
        List<GridBindingDto> gridBindingDtos = gridBindingService.queryList(queryMap);

        Iterator<GridBindingDto> iterator = gridBindingDtos.iterator();
        while (iterator.hasNext()) {
            for (int i = 0; i < gridBindingDtos.size(); i++) {
                GridBindingDto gridBindingDto = gridBindingDtos.get(i);
                if (gridId.equals(gridBindingDto.getSourceId())) {
                    iterator.remove();
                }
            }
        }
        List<VillageBuildingDto> list = new ArrayList<>();
        for (GridBindingDto bind : gridBindingDtos) {
            VillageBuildingDto buildingDto = villageBuildingService.selectCacheById(bind.getSourceId());
            if (buildingDto != null) {
                list.add(buildingDto);
            }
        }

        return Response.<List<VillageBuildingDto>>ok().wrap(list);
    }

    /**
     * 网格楼栋搜索，已经绑定不展示
     */
    @GetMapping("queryAllBuilding")
    @Operation(summary = "查询权限下的小区楼栋列表")
    public Response<List<VillageBuildingDto>> queryAllBuilding() {

        Map<String, Object> params = Request.parseParams(httpServletRequest);
        super.fillAuthorityData(params);
        List<VillageBuildingDto> list = villageBuildingService.queryList(params);
        return Response.<List<VillageBuildingDto>>ok().wrap(list);
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "grid:list")
    @Operation(summary = "网格的分页查询列表")
    public Response<Page<GridDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = gridService.queryTotal(request.getParams());

        List<GridDto> list = null;
        if (total > 0) {
            list = gridService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<GridDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "grid:edit")
    @Operation(summary = "查询单条网格记录")
    public Response<GridDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridDto gridDto = gridService.selectById(id);

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put(LambdaUtil.getFieldName(GridBindingDto::getSourceType), GridConstant.SourceType.BUILDING.getType());
        queryMap.put(LambdaUtil.getFieldName(GridBindingDto::getGridId), id);
        List<GridBindingDto> gridBindingDtos = gridBindingService.queryList(queryMap);
        List<VillageBuildingDto> buildingList = new ArrayList<>();
        for (GridBindingDto village : gridBindingDtos) {
            VillageBuildingDto building = villageBuildingService.selectCacheById(village.getSourceId());
            buildingList.add(building);
        }
        gridDto.setBuildingList(buildingList);

        queryMap.remove(LambdaUtil.getFieldName(GridBindingDto::getSourceType));
        queryMap.put(LambdaUtil.getFieldName(GridBindingDto::getSourceType), GridConstant.SourceType.COMPANY.getType());
        List<GridBindingDto> reallyCompanyDtos = gridBindingService.queryList(queryMap);
        List<ReallyCompanyDto> companyList = new ArrayList<>();
        for (GridBindingDto company : reallyCompanyDtos) {
            ReallyCompanyDto reallyCompany = reallyCompanyService.selectCacheById(company.getSourceId());
            companyList.add(reallyCompany);
        }
        gridDto.setCompanyList(companyList);

        return Response.<GridDto>ok().wrap(gridDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "grid:info")
    @Operation(summary = "查询单条网格记录")
    public Response<GridDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (gridService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridDto gridDto = gridService.selectById(id);

        return Response.<GridDto>ok().wrap(gridDto);
    }

    /**
     * 保存
     *
     * @param gridDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "grid:edit")
    @Operation(summary = "保存单条网格记录")
    public Response<Object> save(@RequestBody @Validated GridDto gridDto) {

        //填充基础数据
        fillSaveCommonData(gridDto);

        if (CollectionUtils.isEmpty(gridDto.getBuildingList()) && CollectionUtils.isEmpty(gridDto.getCompanyList())) {
            return Response.error("楼栋单位不可都为空");
        }
        gridDto.setExtraAttr(JacksonUtils.toJsonString(gridDto.getExtraAttrCls()));

        gridService.saveOrUpdate(gridDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param gridDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "grid:edit")
    @Operation(summary = "修改单条网格记录")
    public Response<Object> update(@RequestBody @Validated GridDto gridDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(gridDto.getId()));
        if (gridService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(gridDto);

        if (CollectionUtils.isEmpty(gridDto.getBuildingList()) && CollectionUtils.isEmpty(gridDto.getCompanyList())) {
            return Response.error("楼栋单位不可都为空");
        }

        gridDto.setExtraAttr(JacksonUtils.toJsonString(gridDto.getExtraAttrCls()));

        gridService.saveOrUpdate(gridDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "grid:delete")
    @Operation(summary = "批量删除存在的网格记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (gridService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        gridService.deleteBatch(ids);

        return Response.ok();
    }
}
